<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/1/23
 * Time: 9:57
 * 首页相关控制器
 */
namespace app\admin\controller;
use app\common\controller\Common;
use app\index\controller\Base;
use app\index\model\Role;
use think\Config;
use think\Db;
use think\Exception;
use think\Session;
use think\Validate;

class System extends Base
{
    /**
     * 首页html展示
     * @return mixed
     */
    public function index()
    {
        //权限查询
        $common = new Common();
        $powerList = $common->showpower();
        $this->assign("powerList",$powerList);

        if(!empty($_GET['type'])) {
            try{
                $page = empty($_GET['page']) ? 1 : $_GET['page'];
                $limit = empty($_GET['limit']) ? 10 : $_GET['limit'];
                $start = ($page - 1) * $limit;
                $where = [];
                if(!empty($_GET['platform'])){
                    $platform = $_GET['platform'];
                    $where['name']=  ['like',"%".$platform."%"];
                }
                //查询公众号列表
                $list = Db::name("config")->where($where)->order("id desc")->limit($start,$limit)->select();

                foreach ($list as $k=>$v){
                    $list[$k]['addtime'] = date("Y-m-d H:i:s",$v['addtime']);

                    $v['avatar'] = empty($v['avatar']) ? "/static/images/nopic-107.png" : $v['avatar'];
                    $list[$k]['avatar'] = "<img src='".$v['avatar']."' style='max-height:75px;max-width:60px;'>";
                }

                $count = Db::name("config")->where($where)->count();
                $black['code'] = 0;
                $black['data'] = $list;
                $black['count'] = $count;
            }catch (Exception $e){
                $black['code'] = 202;
                $black['msg'] = $e->getMessage();
            }
            return $black;
        }


        return $this->fetch("index");
    }

    //删除文件夹代码
    public function delFolder($path){
        //如果是目录则继续
        if(is_dir($path)){
            //扫描一个文件夹内的所有文件夹和文件并返回数组
            $p = scandir($path);
            if(count($p)==2){
                @rmdir($path);
            }
            foreach($p as $val){
                //排除目录中的.和..
                if($val !="." && $val !=".."){
                    //如果是目录则递归子目录，继续操作
                    if(is_dir($path."/".$val)){
                        //子目录中操作删除文件夹和文件
                        $this->delFolder($path.'/'.$val.'/');
                        //目录清空后删除空文件夹
                        @rmdir($path.'/'.$val);
                    }else{
                        //如果是文件直接删除
                        unlink($path.$val);
                    }
                }
            }
            $this->delFolder($path);
        }
    }


    //删除公众号
    public function delConfig(){
        try{

            $id = $_POST['id'];

            $where['id'] = $id;
            $name = Db::name("config")->where($where)->value('name');
            Db::name("config")->where($where)->delete();

            //删除文件夹
            $path = ROOT_PATH . 'public' . DS . 'upload'.DS."platform".$id;
            $this->delFolder($path);

            $common = new Common();
            $log['remark'] = "管理员【" . Session::get("user_name") . "】删除公众平台【".$name."】";
            $log['controller'] = "System";
            $log['methods'] = "delConfig";
            $common->addLog($log);
            Session::delete("thisWechat");

            $black['code'] =0;
            $black['msg'] = "操作成功";
        }catch (Exception $e){
            $black['code'] =202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }


    //生成token
    public function createtoken(){
        //ABCDEFGHIJKLMNOPQRSTUVWXYZ
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        mt_srand(10000000*(double)microtime());
        for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < 32; $i++){
            $str .= $chars[mt_rand(0, $lc)];
        }
        try{
            $black['code'] =0;
            $black['token'] = $str;
            $black['msg'] = "操作成功";
        }catch (Exception $e){
            $black['code'] =202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }

    //微信配置
    public function config(){
//        $accounts = Config::get("accounts");
        if($_POST){
            try{
                $rule = [
                    ["appid", "require", "AppId不能为空"],
                    ["appsecret", "require", "AppSecret不能为空"],
//                    ["token", "require", "token不能为空"],
                ];
                $validate = new Validate($rule);
                $request = $this->request->post();
                if (!$validate->check($request)) {
                    throw new Exception($validate->getError());
                }
                /*$sql = "SELECT * FROM `yunos_config` WHERE `id` <> 1 OR `appid` = 'wx10fba0dffa408fcb' OR `xcx_appid` = 'wx598641c99deb8edd'";
                $detail = Db::query($sql);*/



                $where = "(appid='".$_POST['appid']."' or xcx_appid='". $_POST['xcx_appid']."')";
                if(!empty($_POST['id'])){
                    $where .=" and id!=".$_POST['id'];
                }
                $detail = Db::name("config")->where($where)->find();

                if(!empty($detail)){
                    throw new Exception("该公众号信息已存在请勿重复添加");
                }

                $insert['appid'] = $_POST['appid'];
                $insert['appsecret'] = $_POST['appsecret'];
                $insert['token'] = $_POST['token'];
                $insert['name'] = $_POST['name'];
                $insert['desc'] = $_POST['desc'];
                $insert['account'] = $_POST['account'];
                $insert['primeval'] = $_POST['primeval'];
                $insert['type'] = $_POST['type'];
                $insert['avatar'] = empty($_POST['avatar'])?'':$_POST['avatar'];
                $insert['qr_code'] = empty($_POST['qr_code'])?'':$_POST['qr_code'];
                $insert['EncodingAESKey'] = $_POST['EncodingAESKey'];

                $insert['xcx_appid'] = $_POST['xcx_appid'];
                $insert['xcx_appsecret'] = $_POST['xcx_appsecret'];
                $insert['xcx_code'] = $_POST['xcx_code'];

//                $insert['wechat_mch_id'] = $_POST['wechat_mch_id'];
//                $insert['wechat_key'] = $_POST['wechat_key'];
                if(empty($_POST['id'])){
                    $insert['addtime'] = time();
                    $insert['add_id'] = Session::get("id");
                    $res = Db::name("config")->insertGetId($insert);
                    $log['remark'] = "管理员【" . Session::get("user_name") . "】新增微信平台【".$_POST['name']."】关联id【".$res."】";
                }else{
                    $insert['updatetime'] = time();
                    $insert['update_id'] = Session::get("id");
                    $res = Db::name("config")->where(['id'=>$_POST['id']])->update($insert);
                    $log['remark'] = "管理员【" . Session::get("user_name") . "】修改微信平台【".$_POST['name']."】关联id【".$_POST['id']."】";
                }
                $common = new Common();
                $log['controller'] = "System";
                $log['methods'] = "config";
                $common->addLog($log);
                if(empty($res)){
                    throw new Exception("非法操作");
                }
                $black['code'] =0;
                $black['msg'] = "操作成功";
            }catch (Exception $e){
                $black['code'] =202;
                $black['msg'] = $e->getMessage();
            }
            return $black;
        }else{
            $id = empty($_GET['id'])?'':$_GET['id'];
            $accounts = Db::name("config_attribute")->where(['key'=>"accounts"])->value("value");
            $accounts = explode("|",$accounts);
            foreach ($accounts as $k=>$v){
                $accounts[$k+1] = $v;
            }
            unset($accounts[0]);
            $config = Db::name("config")->where(['id'=>$id])->find();
            $data['accounts'] = $accounts;
            $data['config'] = $config;
            $this->assign($data);
        }
        return $this->fetch("config");
    }

    //平台配置
    public function platform(){
        //权限查询
        $common = new Common();
        $powerList = $common->showpower();
        $this->assign("powerList",$powerList);

        $config = Db::name("config_platform")->find();
        $data['config'] = $config;
        $this->assign($data);

        if($_POST){

            try{
                $rule = [
                    ["name", "require", "平台名称不能为空"],
                    ["logo", "require", "logo不能为空"],
//                    ["token", "require", "token不能为空"],
                ];
                $validate = new Validate($rule);
                $request = $this->request->post();
                if (!$validate->check($request)) {
                    throw new Exception($validate->getError());
                }
                $insert['name'] = $_POST['name'];
                $insert['description'] = $_POST['description'];
                $insert['logo'] = $_POST['logo'];
                $insert['socket'] = $_POST['socket'];
                $insert['title'] = $_POST['title'];
                $insert['keywords'] = $_POST['keywords'];


//                $insert['show_view'] = $_POST['show_view'];
                $config = Db::name("config")->find();
                if(empty($config)){
                    $insert['updatetime'] = time();
                    $insert['update_id'] = Session::get("id");
                    $res = Db::name("config_platform")->insertGetId($insert);
                }else{
                    $insert['updatetime'] = time();
                    $insert['update_id'] = Session::get("id");
                    $res = Db::name("config_platform")->where(['id'=>$config['id']])->update($insert);
                }

                if(empty($res)){
                    throw new Exception("非法操作");
                }
                $black['code'] =0;
                $black['msg'] = "操作成功";
            }catch (Exception $e){
                $black['code'] =202;
                $black['msg'] = $e->getMessage();
            }
            return $black;
        }


        return $this->fetch("platform");
    }


    //添加视图
    public function addSlide()
    {
        $return = [];
        if(!empty($_POST['id'])){
            $id = $_POST['id'];
            $detail = Db::name("slide")->where(['id'=>$id])->find();
            $return['detail'] = $detail;
            $this->assign($return);
            return view("editslide");
        }else{
            $this->assign($return);
            return view("addslide");
        }
    }

    //更改状态
    public function slideStatus(){
        try{
            $id = $_POST['id'];
            $type = $_POST['type'];
            $status = $_POST['status'];
            $res = Db::name("config")->where(['id'=>$id])->update([$type=>$status]);
            if(empty($res)){
                throw new Exception("非法操作");
            }
            $detail = Db::name("config")->where(['id'=>$id])->find();
            $status = ($status==1)?"启用":"禁用";
            $common = new Common();
            $log['remark'] = "管理员【" . Session::get("user_name") . "】将微信平台【".$detail['name']."】的状态更新为【".$status."】";
            $log['controller'] = "System";
            $log['methods'] = "slideStatus";
            $common->addLog($log);
            $black['status'] = 'success';
            $black['msg'] = "操作成功";
        }catch (Exception $e){
            $black['status'] = 'error';
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }

    //属性配置
    public function attribute(){
        //权限查询
        $common = new Common();
        $powerList = $common->showpower();
        $this->assign("powerList",$powerList);

        if(!empty($_GET['type'])){
            try {
                $page = empty($_GET['page']) ? 1 : $_GET['page'];
                $limit = empty($_GET['limit']) ? 10 : $_GET['limit'];
                $start = ($page - 1) * $limit;
                //链表查询
                $list = Db::name("config_attribute")->order("id desc")->limit($start,$limit)->select();
                $count = Db::name("config_attribute")->order("id desc")->count("*");
                $black['code'] = 0;
                $black['data'] = $list;
                $black['count'] = $count;
            }catch (Exception $e){
                $black['code'] = 202;
                $black['msg'] = $e->getMessage();
            }
            return $black;
        }


        return view("attribute");
    }

    //添加视图
    public function addAttribute(){

        if(empty($_POST['type'])){
            try{
                $rule = [
                    ["name", "require", "名称不能为空"],
                    ["key", "require", "Key不能为空"],
                    ["value", "require", "值不能为空"],
                ];

                $validate = new Validate($rule);
                $data = $this->request->post();
                if (!$validate->check($data)) {
                    throw new Exception($validate->getError());
                }

                if(!empty($data['id'])){
                    $where['id'] = ['neq',$data['id']];
                }
                $where['key'] = $data['key'];
                //查询Key是否存在
                $detail = Db::name("config_attribute")->where($where)->value("id");
                if(!empty($detail)){
                    throw new Exception("该KEY值已存在");
                }


                if(empty($data['id'])){
                    $data['addtime'] = time();
                    $data['add_id'] = Session::get("id");
                    Db::name("config_attribute")->insertGetId($data);
                }else{
                    $data['updatetime'] = time();
                    $data['updatetime'] = Session::get("id");
                    Db::name("config_attribute")->where(['id'=>$data['id']])->update($data);
                }




                $black['status'] = 'success';
                $black['msg'] = "操作成功";
            }catch (Exception $e){
                $black['status'] = 'error';
                $black['msg'] = $e->getMessage();
            }
            return $black;


        }else{
            if(empty($_POST['id'])){
                return view("addattribute");
            }else{
                $detail = Db::name("config_attribute")->where(['id'=>$_POST['id']])->find();
                $assign = [
                    "detail" => $detail,
                ];
                $this->assign($assign);
                return view("saveattribute");
            }
        }



    }



    public function doSlide(){

        try{
            $rule = [
                ["title", "require", "请填写名称"],
                ["thumb", "require", "请选择图片"],
            ];
            $validate = new Validate($rule);
            $request = $this->request->post();
            if (!$validate->check($request)) {
                $this->msg($validate->getError(), "添加信息", "error");
            }


            $data = $_POST;

            $data['addtime'] = time();
            $data['add_id'] = Session::get("id");
            if(empty($data['id'])){
                $res = Db::name("slide")->insertGetId($data);
            }else{
                $id = $data['id'];
                unset($data['id']);
                $res = Db::name("slide")->where(['id'=>$id])->update($data);
            }


            if(empty($res)){
                throw new Exception("非法操作");
            }
            $black['status'] = 'success';
            $black['msg'] = "操作成功";
        }catch (Exception $e){
            $black['status'] = 'error';
            $black['msg'] = $e->getMessage();
        }
        return $black;

    }

}
